package org.teachertools.web.tag;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.Globals;
import org.apache.struts.taglib.TagUtils;

public class DeleteButtonTag extends BodyTagSupport {
    private static final long serialVersionUID = -7587022864863039776L;

    private String formName = null;

    @Override
    public int doStartTag() {
        return BodyTag.SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspTagException {

        JspWriter out = this.pageContext.getOut();
        try {
            Object form = this.pageContext.getRequest().getAttribute(this.formName);

            boolean disable = isDisable(form);

            out.println("<input type=\"submit\" " + (disable ? " disabled=\"disabled\"" : "")
                    + " name=\"submit\" value=\"" + getLocalizedMessage("button.delete")
                    + "\" onclick=\"javascript:return confirm('" + getLocalizedMessage("button.confirmSuppress")
                    + "');\">");
        } catch (Exception e) {
            throw new JspTagException("Error rendering delete button", e);
        }

        return BodyTag.EVAL_PAGE;
    }

    protected String getLocalizedMessage(String key) throws JspException {
        // return I18nUtils.getMessage(this.pageContext, key);
        // Retrieve the message string we are looking for
        String message = TagUtils.getInstance()
                .message(this.pageContext, Globals.MESSAGES_KEY, Globals.LOCALE_KEY, key);
        return message;
    }

    private boolean isDisable(Object form) throws IntrospectionException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        Object value;
        try {
            value = PropertyUtils.getProperty(form, "isUpdate");
        } catch (NoSuchMethodException e) {
            value = null;
        }

        if (value == null || ((Boolean) value).booleanValue() == false) {
            return true;
        }
        return false;
    }

    public String getFormName() {
        return this.formName;
    }

    public void setFormName(String pFormName) {
        this.formName = pFormName;
    }
}
